﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    public partial class ComicDownloadPage : PhoneApplicationPage
    {
        private string jsonDownloadComic = string.Empty;
        private DownloadComic downloadComic = null;
        private string cacheDataKey = string.Concat(KEYS.CacheDownloadQueuePrefix, "ALL");
        ///comic/comicsread_v3?bookid=17089&partid=226003&partVersion=1 HTTP/1.1
        public ComicDownloadPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (base.NavigationContext.QueryString.ContainsKey("DownloadComic"))
            {

                base.NavigationContext.QueryString.TryGetValue("DownloadComic", out jsonDownloadComic);
                if (string.IsNullOrWhiteSpace(jsonDownloadComic))
                {
                    base.NavigationService.GoBack();
                    return;
                }
                downloadComic = JSONHelper.Deserialize<DownloadComic>(jsonDownloadComic);
                if (downloadComic == null)
                {
                    base.NavigationService.GoBack();
                    return;
                }
                //新增或更新本地缓存（要下载漫画的缓存列中）
                this.InsertOrUpdateLocalCache();
                //添加至下载队列中去
                InsertOrUpdateDownloadQueue();
            }
            //加载下载过的漫画列表
            LoadDownloadQueueComics();
        }

        private void gridComic_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            DownloadComic item = (sender as Grid).DataContext as DownloadComic;
            if (item == null)
                return;
            NaviService.Navigate(ComicIslandPage.ComicDownloadChapterPage,
                string.Concat("?jsonDownloadComic=", Uri.EscapeDataString(JSONHelper.Serialize<DownloadComic>(item))));
        }

        /// <summary>
        /// 新增或更新本地缓存
        /// </summary>
        void InsertOrUpdateLocalCache()
        {
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey, false);
            var items = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(cacheHelper.LocalCacheData);
            bool isUpdate = false;
            if (items != null && items.Count > 0)
            {
                DownloadComic existDownloadComic = null;
                foreach (DownloadComic item in items)
                {
                    if (item.ComicId == downloadComic.ComicId)
                    {
                        //已经存在则需要一一比对
                        isUpdate = true;
                        existDownloadComic = item;
                        break;
                    }
                }
                //TODO 如果是更新则需要一一比对来进行数据更新，如果是false则直接加入列表
                if (!isUpdate)
                {
                    items.Add(downloadComic);
                    string jsonSerialize = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(items);
                    cacheHelper.SetDataToLocalCache(cacheDataKey, jsonSerialize);
                }
                else
                {
                    //TODO 比对更新
                }
            }
            else
            {
                string jsonSerialize = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(new ObservableCollection<DownloadComic>() { downloadComic });
                cacheHelper.SetDataToLocalCache(cacheDataKey, jsonSerialize);
            }
        }


        #region ******************************加载缓存的漫画列表及其多选删除操作等******************************
        /// <summary>
        /// 加载缓存的漫画列表
        /// </summary>
        void LoadDownloadQueueComics()
        {
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey, false);
            var items = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(cacheHelper.LocalCacheData);
            if (!(items != null && items.Count > 0))
            {
                //为空，则不处理
                return;
            }
            foreach (DownloadComic item in items)
            {
                if (item == null)
                    continue;
                if (!(item.Chapters != null && item.Chapters.Count > 0))
                    continue;
                item.Total = item.Chapters.Count;
                item.TotalCompleted = item.Chapters.Where(p => p.DownloadStatus == (int)DownloadComicChapterStatus.Completed).Count();
            }
            this.Dispatcher.BeginInvoke(() =>
            {
                this.llms.ItemsSource = items;
            });
        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("选择".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "删除";
                    appBarIcon.IconUri = new Uri("/Images/Icons/delete.png", UriKind.Relative);
                    appBarIcon.IsEnabled = false;
                    this.llms.IsSelectionEnabled = true;
                }
                else
                {
                    if (MessageBoxResult.OK == MessageBox.Show(string.Format("确认删除选中的 {0} 个缓存漫画？", this.llms.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
                    {
                        LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
                        cacheHelper.GetDataFromLocalCache(cacheDataKey, false);
                        var dcs = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(cacheHelper.LocalCacheData);
                        //
                        var source = this.llms.ItemsSource as ObservableCollection<DownloadComic>;
                        while (this.llms.SelectedItems.Count > 0)
                        {
                            var item = this.llms.SelectedItems[0] as DownloadComic;
                            if (item != null)
                            {
                                if (dcs != null && dcs.Count > 0)
                                {
                                    for (int i = 0; i < dcs.Count; i++)
                                    {
                                        DownloadComic dc = dcs[i];
                                        if (dc == null)
                                            continue;
                                        if (item.ComicId == dc.ComicId && item.ComicTitle.Equals(dc.ComicTitle))
                                        {
                                            dcs.Remove(dc);
                                            break;
                                        }
                                    }
                                }
                                source.Remove(item);
                            }
                        }
                        //更新本地缓存
                        cacheHelper.SetDataToLocalCache(cacheDataKey, JSONHelper.Serialize<ObservableCollection<DownloadComic>>(dcs));
                    }
                    //
                    appBarIcon.Text = "选择";
                    appBarIcon.IconUri = new Uri("/Images/Icons/select.png", UriKind.Relative);
                    appBarIcon.IsEnabled = true;
                    this.llms.IsSelectionEnabled = false;
                }
            });
        }

        private void llms_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.llms.IsSelectionEnabled)
            {
                bool hasSelection = ((this.llms.SelectedItems != null) && (this.llms.SelectedItems.Count > 0));
                var appBarIcon = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
                if (appBarIcon == null)
                    return;
                appBarIcon.IsEnabled = hasSelection;
            }
            else
            {
                bool hasSelection = ((this.llms.SelectedItems != null) && (this.llms.SelectedItems.Count > 0));
                var appBarIcon = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
                if (appBarIcon == null)
                    return;

                if ("删除".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "选择";
                    appBarIcon.IconUri = new Uri("/Images/Icons/select.png", UriKind.Relative);
                    appBarIcon.IsEnabled = true;
                    this.llms.IsSelectionEnabled = false;
                }
            }
        }
        #endregion  ******************************加载缓存的漫画列表及其多选操作等******************************


        #region ******************************新增或更新下载队列******************************
        /// <summary>
        /// 新增或更新下载队列
        /// </summary>
        void InsertOrUpdateDownloadQueue()
        {
            //确保目录/shared/transfers存在
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isoStore.DirectoryExists("/shared/transfers"))
                {
                    isoStore.CreateDirectory("/shared/transfers");
                }
            }
            //BackgroundTransferService限制数
            int currentRequests = BackgroundTransferService.Requests.Count();
            if (BackgroundTransferService.Requests.Count() >= 25)
            {
                return;
            }
            //读取缓存数据
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey, false);
            var items = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(cacheHelper.LocalCacheData);
            if (!(items != null && items.Count > 0))
            {
                //为空，则不处理
                return;
            }
            //获取章节中的25条数据
            ObservableCollection<DownloadComicChapterImage> chapterImagesQueues = new ObservableCollection<DownloadComicChapterImage>();

            foreach (DownloadComic item in items)
            {
                if (item == null)
                    continue;
                if (!(item.Chapters != null && item.Chapters.Count > 0))
                    continue;
                item.Total = item.Chapters.Count;
                //获取等待下载的章节
                var ts = (from p in item.Chapters
                          where p.DownloadStatus == (int)DownloadComicChapterStatus.Pending
                          select p).ToList<DownloadComicChapter>();
                if (ts != null && ts.Count > 0)
                {
                    do
                    {
                        DownloadComicChapter dcc = ts[0];

                        #region 获取漫画章节中的图片地址列表
                        string requestUrl = string.Concat(KEYS.REQUEST_HOST,
                            string.Format("/comic/comicsread_v3?bookid={0}&partid={1}&partVersion=3", item.ComicId, dcc.PartId));
                        LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());

                        WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
                        IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
                        {
                            try
                            {
                                this.Dispatcher.BeginInvoke(() =>
                                {
                                    #region 获取结果处理
                                    string result = webTask.EndWebTask(callBackResult);

                                    if (string.IsNullOrWhiteSpace(result))
                                    {
                                        LogHelper.LogError("Result is empty.");
                                        //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                                        return;
                                    }
                                    //
                                    if (result.StartsWith("exception:"))
                                    {
                                        LogHelper.LogError(result);
                                        return;
                                    }
                                    LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                                    //

                                    var rootCharacterString = JSONHelper.Deserialize<JsonComicContent>(result);
                                    if (!(rootCharacterString != null && !string.IsNullOrWhiteSpace(rootCharacterString.Info)))
                                    {
                                        //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                                    }
                                    else
                                    {
                                        var itemsource = JSONHelper.Deserialize<ObservableCollection<JsonComicContentInfo>>(rootCharacterString.Info);
                                        if (itemsource != null && itemsource.Count > 0)
                                        {
                                            var comicImages = new ObservableCollection<DownloadComicChapterImage>();
                                            foreach (JsonComicContentInfo jcci in itemsource)
                                            {
                                                comicImages.Add(new DownloadComicChapterImage()
                                                {
                                                    ComicId = item.ComicId,
                                                    PartId = dcc.PartId,
                                                    ImageUrl = jcci.Imgurl,
                                                    Referer = jcci.Referer,
                                                    DownloadStatus = (int)DownloadComicChapterStatus.Pending
                                                });
                                                dcc.Images = comicImages;
                                            }
                                            //
                                            chapterImagesQueues = comicImages;
                                            if (chapterImagesQueues != null && chapterImagesQueues.Count > 0)
                                            {
                                                foreach (DownloadComicChapterImage dcci in chapterImagesQueues)
                                                {
                                                    if (BackgroundTransferService.Requests.Count() >= 25)
                                                    {
                                                        break;
                                                    }
                                                    Uri transferUri = new Uri(Uri.EscapeUriString(dcci.ImageUrl), UriKind.RelativeOrAbsolute);
                                                    BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
                                                    transferRequest.Method = "GET";
                                                    Uri downloadUri = new Uri(string.Concat("shared/transfers/", KEYS.CacheImagePrefix, dcci.ComicId, "_", dcci.PartId, "_", MD5.GetMd5String(dcci.ImageUrl)), UriKind.RelativeOrAbsolute);
                                                    transferRequest.DownloadLocation = downloadUri;
                                                    LogHelper.LogInfo(downloadUri.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                                                    //
                                                    transferRequest.Tag = JSONHelper.Serialize<ObservableCollection<DownloadComicChapterImage>>(chapterImagesQueues);
                                                    transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                                                    try
                                                    {
                                                        BackgroundTransferService.Add(transferRequest);
                                                    }
                                                    catch (Exception err) { LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod()); }
                                                }
                                            }
                                            //
                                        }
                                    }
                                    #endregion 获取结果处理
                                });
                            }
                            catch (Exception err)
                            {

                            }
                        }, webTask);
                        #endregion 获取漫画章节中的图片地址列表

                    } while (false);
                }
            }
        }
        #endregion ******************************新增或更新下载队列******************************
    }
}